package com.fly.controller;


import com.fly.bean.*;
import com.fly.service.TaskService;
import com.fly.util.Msg;
import com.fly.util.Page;
import com.fly.vo.*;
import org.ietf.jgss.Oid;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.crypto.Data;
import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class TaskController {

    @Autowired
    TaskService taskService;

    //按条件查询任务分页
    @RequestMapping("/selectTasksByConditionS")
    @ResponseBody
    public Msg selectTaskByCondition(TaskPageVoScw taskPageVoScw,
                                     Page page
//            @RequestParam("userName") String userName,
//
//            @RequestParam("startDate") Date leftDate,
//
//            @RequestParam("endDate") Date rightDate,
//
//            @RequestParam("taskNo") String taskNo,
//
//            @RequestParam("circuitryNo") String circuitryNo,
//
//            @RequestParam("id") Integer id,
//
//            @RequestParam("pageSize") Integer pageSize,
//
//            @RequestParam("currentPage") Integer currentPage

                                                                ){

        TaskVoScw taskVoScw = new TaskVoScw();

        if (taskPageVoScw.getCircuitryNo() != null){
            taskVoScw.setCircuitryNo("%"+taskPageVoScw.getCircuitryNo()+"%");
        }
        if (taskPageVoScw.getTaskNo() != null){
            taskVoScw.setTaskNo("%"+taskPageVoScw.getTaskNo()+"%");
        }
        if (taskPageVoScw.getUserName() != null){
            taskVoScw.setUserName("%"+taskPageVoScw.getUserName()+"%");
        }

        taskVoScw.setLeftDate(taskPageVoScw.getStartDate());
        taskVoScw.setRightDate(taskPageVoScw.getEndDate());
        taskVoScw.setId(taskPageVoScw.getId());
        //总记录数

        int count = taskService.getTaskCountByConditionS(taskVoScw);
        page.setCount(count);
        taskVoScw.setPage(page);
//        userName=ZhangSan&startDate=2019/10/10&endDate=2019/10/30&taskNo=XW1911270001&circuitryNo=XW0001&id=8&currentPage=1
        List<Task> tasks = taskService.getTaskByConditionS(taskVoScw);

        return Msg.success().add("tasks",tasks).add("count",page.getCount());
    }

    //显示所有线路的名称
    @RequestMapping("/showCircuitryNamesS")
    @ResponseBody
    public Msg showCircuitryNames(){
        List<Circuitry> circuitryNames = taskService.getCircuitryNameAndIdS();
        return Msg.success().add("circuitryNames",circuitryNames);
    }

    //显示所有巡检员名称
    @RequestMapping("/showInspectorsNamesS")
    @ResponseBody
    public Msg showInspectorsNames(){
        List<Users> inspectorNames = taskService.getAllInspectorsS();
        return Msg.success().add("inspectorNames",inspectorNames);
    }

    //制定巡检任务
    @RequestMapping("/createTasksS")
    @ResponseBody
    public Msg createTasks(@RequestParam("taskName") String taskName,
                           @RequestParam("taskNo") String taskNo,
                           @RequestParam("circuitryId") Integer circuitryId,
                           @RequestParam("createDate") Date createDate,
                           @RequestParam("taskNote") String taskNote,
                           @RequestParam("inspectorId") String inspectorId,
                           @RequestParam("userId") Integer userId,
                           @RequestParam("startPoleNo") String startPoleNo,
                           @RequestParam("endPoleNo") String endPoleNo){

        TaskPoleRelation taskPoleRelation = new TaskPoleRelation();
        taskPoleRelation.setStartPoleNo(startPoleNo);
        taskPoleRelation.setEndPoleNo(endPoleNo);

        TaskVoScw taskVoScw = new TaskVoScw();

        if (inspectorId == ""){
            taskVoScw.setTaskState(7);
        }else {
            taskVoScw.setTaskState(8);
        }

        taskVoScw.setTaskName(taskName);
        taskVoScw.setTaskNo(taskNo);
        taskVoScw.setCircuitryId(circuitryId);
        taskVoScw.setCreateDate(createDate);
        taskVoScw.setTaskNote(taskNote);
        taskVoScw.setUserId(userId);
        taskVoScw.setTaskType(1);
        taskVoScw.setTaskPoleRelation(taskPoleRelation);

        int row = taskService.addTaskS(taskVoScw);

        if (row > 0){
            int taskId = taskService.getTaskOrderByIdS();
            taskVoScw.setTaskId(taskId);
            if (inspectorId != ""){

                String inspectorIds[]= (inspectorId).split(",");

                for (String s:inspectorIds){
                    taskVoScw.setUserId(Integer.parseInt(s));
                    taskService.addTURelationS(taskVoScw);
                }

            }
            int row2 = taskService.addTaskPoleRS(taskVoScw);
            if ((row2 > 0)){
                return Msg.success().add("ifSuccess","success");
            }
        }
        return Msg.fail().add("ifSuccess","fail");
    }
    //制定巡检任务自动生成任务编码
    @RequestMapping("/autoCreateTaskNoS")
    @ResponseBody
    public Msg autoCreateTaskNo(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
        Date date = new Date();
        String autoTaskNo = "RXJ"+simpleDateFormat.format(date)+(new Date().getTime()+"").substring(4,9);
        return Msg.success().add("autoTaskNo",autoTaskNo);
    }

    //通过线路Id查询对应的杆号
    @RequestMapping("/selectPoleNoByCircuitryIdS")
    @ResponseBody
    public Msg selectPoleNoByCircuitryIdS(Integer circuitryId){
        Circuitry circuitry = new Circuitry();
        circuitry.setCircuitryId(circuitryId);
        List<Pole> poles = taskService.selectPolesByCircuitryIdS(circuitry);
        return Msg.success().add("poles",poles);
    }

    //查询所有所有的任务到分页列表
    @RequestMapping("/showAllTasksByPageS")
    @ResponseBody
    public Msg showAllTasksByPage(Integer pageSize,
                                  Integer currentPage){
        Page page = new Page();
        page.setPageSize(pageSize);
        page.setCurrentPage(currentPage);
        List<Task> tasks = taskService.getAllTasksByPageS(page);
//        System.out.println(tasks);
        //需要前端传当前页过来currentPage

        //总记录数
        int count = taskService.getTaskTotalCountS(page);
        page.setCount(count);
        return Msg.success().add("tasks",tasks).add("count",page.getCount());
    }

    //通过TaskId查询所分配的巡检员(修改巡检任务)
    @RequestMapping("/showInspectorsByTaskIdS")
    @ResponseBody
    public Msg showInspectorsByTaskIdS(@RequestParam("taskId") Integer taskId){

        List<Users> inspectorNames = taskService.getInspectorsByTaskIdS(taskId);

        return Msg.success().add("inspectorNames",inspectorNames);
    }
//    //通过线路id查询起始杆id和终止杆id(修改巡检任务)
//    @RequestMapping("/showStartEndPoleIdS")
//    @ResponseBody
//    public Msg showStartAndEndPoleIdByCircuitryId(@RequestParam("circuitryId") Integer circuitryId){
//
//        List<Circuitry> startEndPoleId = taskService.getStartAndEndPoleIdByCircuitryIdS(circuitryId);
////        for (Circuitry ids:startEndPoleId){
////            int minPoleNum = ids.getStartPole().getPoleId();
////            int maxPoleNum = ids.getEndPole().getPoleId();
////            System.out.println(minPoleNum+"~"+maxPoleNum);
////        }
//        return Msg.success().add("startEndPoleId",startEndPoleId);
//    }

    //修改巡检任务
    @RequestMapping("/changeTaskS")
    @ResponseBody
    public Msg changeTaskS(String taskNo,
                           String taskName,
                           Integer circuitryId,
                           String taskNote,
                           String userId,
                           Integer taskId,
                           String startPoleNo,
                           String endPoleNo){

        TaskPoleRelation taskPoleRelation = new TaskPoleRelation();
        taskPoleRelation.setStartPoleNo(startPoleNo);
        taskPoleRelation.setEndPoleNo(endPoleNo);
        TaskVoScw taskVoScw  = new TaskVoScw();
        taskVoScw.setTaskNo(taskNo);
        taskVoScw.setTaskName(taskName);
        taskVoScw.setCircuitryId(circuitryId);
        taskVoScw.setTaskNote(taskNote);
        taskVoScw.setTaskId(taskId);
        taskVoScw.setTaskPoleRelation(taskPoleRelation);

        //修改task表
        int row = taskService.updateTaskS(taskVoScw);
        int row2 =0;

        //删除task_user_relation表中的对应taskId的数据
        int dRow = taskService.deleteTaskUserRelS(taskVoScw);

        //判断修改页面传过来的巡检员是否为空，不为空才向task_user_relation表中的对应taskId的数据
        if (userId != ""){
            //添加task_user_relation表中的对应taskId的数据
            String userIds[] = userId.split(",");

            for (String id:userIds){
                taskVoScw.setUserId(Integer.parseInt(id));
                row2 = taskService.addTURelationS(taskVoScw);
            }
            //将任务状态改为已分配
            taskService.changeTaskStateByTaskIdS(taskId);

        }else if (userId == ""){
            //如果修改后的巡检员为空，则将任务状态改为待分配
            taskService.changeTaskStateUnassigned(taskId);
        }

        //删除task_pole_relation中的taskId对应的数据
        int row3 = taskService.deleteTaskPoleRel2S(taskVoScw);

        //添加task_pole_relation中的taskId对应的数据
        int row4= taskService.addTaskPoleRel2S(taskVoScw);


        if ((row>0)&&(dRow>0)&&(row2>0)&&(row3>0)&&(row4>0)){
            return Msg.success().add("ifSuccess","success");
        }
        return Msg.fail().add("ifSuccess","fail");
    }
    //分配任务
    //添加task_user_relation中taskId对应的数据
    @RequestMapping("/assignTaskS")
    @ResponseBody
    public Msg assignInsertTaskUserRel2S(String userId,Integer taskId){

        String userIds[] = userId.split(",");

        TaskVoScw taskVoScw  = new TaskVoScw();

        taskVoScw.setTaskId(taskId);

        int row = 0;

        //向task_user_relation中插入所分配的巡检员

        if (userId !=null){
            for (String id:userIds){
                taskVoScw.setUserId(Integer.parseInt(id));
                row = taskService.assignInsertTaskUserRel2S(taskVoScw);
            }
        }
        if (row>0){
            //插入成功后，更改task表中的taskState为已分配
            int row2 = taskService.changeTaskStateByTaskIdS(taskId);
            if (row2 > 0){
                return Msg.success().add("ifSuccess","success");
            }
        }
        return Msg.fail().add("ifSuccess","fail");
    }
    //查看任务
    @RequestMapping("/checkMissionS")
    @ResponseBody
    public Msg checkMissionSelectTasksS(Integer taskId){
        Task task = new Task();
        task.setTaskId(taskId);
        CheckTaskStateVoScw checkTaskStateVoScw = new CheckTaskStateVoScw();
        checkTaskStateVoScw.setTaskId(taskId);
        List<CheckTaskStateVoScw> taskInfo = taskService.checkMissionSelectTasksS(checkTaskStateVoScw);

        //在task_user_relation中查询该任务下的所有巡检员id
        List<Users> usersId = taskService.checkSelectInspectorsIdByTaskIdS(task);
        List<Users> inspectors = new ArrayList<>();

        //通过巡检员Id查询名字
        for (Users id:usersId){
            inspectors.add(taskService.checkSelectInspectorsByUserIdS(id));
        }
//        Circuitry circuitry = new Circuitry();
//        circuitry.setCircuitryId(circuitryId);
        //显示任务下分配了的所有杆
        TaskPoleVoScw taskPoleVoScw = new TaskPoleVoScw();
        taskPoleVoScw.setStartPoleId(taskService.selectStartPoleIdByTaskId(taskId));
        taskPoleVoScw.setEndPoleId(taskService.selectEndPoleIdByTaskId(taskId));


        List<Pole> poles = taskService.checkSelectPolesBetweenPoleIdS(taskPoleVoScw);

        return Msg.success().add("taskInfo",taskInfo).add("inspectors",inspectors).add("poles",poles);
    }

    //杆详情
    @RequestMapping("/showPoleInfosS")
    @ResponseBody
    public Msg showPoleMsgByPoleId(Integer poleId){
        Pole pole = new Pole();
        pole.setPoleId(poleId);
        List<PoleVoScw> poleInfosS=taskService.checkSelectPoleInfosS(pole);

        return Msg.success().add("poleInfosS",poleInfosS);
    }

    //巡检记录统计
    @RequestMapping("/showCensusRecordsS")
    @ResponseBody
    public Msg showCensusRecordsS(TimeVoScw timeVoScw){

        Page page = new Page();
        page.setCurrentPage(timeVoScw.getCurrentPage());
        page.setPageSize(timeVoScw.getPageSize());

        CheckRecordsVoScw checkRecordsVoScw = new CheckRecordsVoScw();
        if (timeVoScw.getTaskNo() !=null){
            checkRecordsVoScw.setTaskNo("%"+timeVoScw.getTaskNo()+"%");
        }
        if (timeVoScw.getCircuitryNo() !=null){
            checkRecordsVoScw.setCircuitryNo("%"+timeVoScw.getCircuitryNo()+"%");
        }
        if (timeVoScw.getHasDefects() !=null){
            checkRecordsVoScw.setHasDefects("%"+timeVoScw.getHasDefects()+"%");
        }

        checkRecordsVoScw.setLeftDate(timeVoScw.getStartDate());
        checkRecordsVoScw.setRightDate(timeVoScw.getEndDate());
        checkRecordsVoScw.setPage(page);

        List<CheckRecordsVoErScw> censusRecords = taskService.censusSelectTaskInfoByIdS(checkRecordsVoScw);
        int count = taskService.censusCountTaskInfoS(checkRecordsVoScw);
        page.setCount(count);
        return Msg.success().add("censusRecords",censusRecords).add("count",page.getCount());
    }

    //取消任务
    @RequestMapping("/cancelTaskS")
    @ResponseBody
    public Msg cancelTaskS(Integer taskId){
        Task task = new Task();
        task.setTaskId(taskId);
        int row = taskService.updateTaskIsCancelS(task);
        if (row > 0 ){
            return Msg.success().add("ifSuccess","success");
        }
        return Msg.fail().add("ifSuccess","fail");
    }

}
